package com.cz.nongyetongv5.activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.ParseException;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.DaiShangChuanListAdapter;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.bean.JianChaDanWei;
import com.cz.nongyetongv5.bean.JianChaHangYe;
import com.cz.nongyetongv5.bean.JianChaNeiRong;
import com.cz.nongyetongv5.bean.JianChaRenYuan;
import com.cz.nongyetongv5.bean.JianDuJianChaRecord;
import com.cz.nongyetongv5.bean.Photo;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.task.UploadDaiShangChuanTask;
import com.cz.nongyetongv5.utils.CharsetUtil;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.DialogUtil;
import com.cz.nongyetongv5.utils.ImageUtil;
import com.cz.nongyetongv5.utils.SerliazableUtil;

public class JianDuJianChaUploadActivity extends Fragment implements
        OnClickListener {

    /**
     * 待上传的ListView
     */
    private ListView lvJianDuJianChaDaiShangChuanList = null;

    /**
     * 数据库工具
     */
    private DatabaseHelper db = null;

    private User user = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.jiandujiancha_daishangchuan,
                container, false);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initConfig();

    }

    /**
     * 初始化视图
     */
    private void initView() {
        lvJianDuJianChaDaiShangChuanList = (ListView) getActivity()
                .findViewById(R.id.lvJianDuJianChaDaiShangChuanList);

    }

    /**
     * 初始化数据配置
     */

    private void initConfig() {

        this.db = new DatabaseHelper(getActivity(), CommonConstants.DBNAME,
                null, CommonConstants.DATABASE_VERSION);

        this.user = (User) getActivity().getIntent().getSerializableExtra(
                "user");

        reloadData();
    }

    /**
     * 刷新数据
     */
    public void reloadData() {
        List<JianDuJianChaRecord> jianDuJianChaRecords = SerliazableUtil
                .getJianDuJianChaRecordByState(1, this.user.getUsername());

        DaiShangChuanListAdapter adpJianDuJianChaListAdapter = new DaiShangChuanListAdapter(
                getActivity(), jianDuJianChaRecords, this);

        lvJianDuJianChaDaiShangChuanList
                .setAdapter(adpJianDuJianChaListAdapter);

    }

    @Override
    public void onClick(View v) {

        if (v instanceof Button) {

            if (v.getId() == R.id.btnDaiShangChuanDelete) {

                if (v.getTag() != null && v.getTag() instanceof Integer) {

                    final int position = (Integer) v.getTag();

                    final CustomDialog deleteDaiShangChuanDialog = new CustomDialog(
                            getActivity());

                    deleteDaiShangChuanDialog
                            .setOnCancleClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    deleteDaiShangChuanDialog.dismiss();
                                }
                            });

                    // 当点击确定的时候
                    deleteDaiShangChuanDialog
                            .setOnActionClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View v) {

                                    DaiShangChuanListAdapter adpJianDuJianChaListAdapter = (DaiShangChuanListAdapter) lvJianDuJianChaDaiShangChuanList
                                            .getAdapter();

                                    if (adpJianDuJianChaListAdapter
                                            .getItem(position) != null
                                            && adpJianDuJianChaListAdapter
                                            .getItem(position) instanceof JianDuJianChaRecord) {

                                        SerliazableUtil
                                                .delete(((JianDuJianChaRecord) adpJianDuJianChaListAdapter
                                                        .getItem(position))
                                                        .getFileId());

                                        // 删除
                                        adpJianDuJianChaListAdapter
                                                .remove(position);

                                        deleteDaiShangChuanDialog.dismiss();

                                        Toast.makeText(getActivity(), "删除成功!",
                                                Toast.LENGTH_SHORT).show();
                                    }

                                }
                            });

                    deleteDaiShangChuanDialog.setMessage(getActivity()
                            .getResources().getString(
                                    R.string.delete_daishangchuan_message));

                    deleteDaiShangChuanDialog.setCancleTxt(getActivity()
                            .getString(R.string.jiandujiancha_item_cancle));

                    deleteDaiShangChuanDialog.setActionTxt(getActivity()
                            .getString(R.string.jiandujiancha_item_sure));

                    deleteDaiShangChuanDialog.show();

                }

            }

            if (v.getId() == R.id.btnDaiShangChuanEdit) {

                final int position = (Integer) v.getTag();

                if (getActivity() instanceof JianDuJianChaMainActivity) {

                    JianDuJianChaMainActivity activity = (JianDuJianChaMainActivity) getActivity();

                    DaiShangChuanListAdapter adpJianDuJianChaListAdapter = (DaiShangChuanListAdapter) lvJianDuJianChaDaiShangChuanList
                            .getAdapter();

                    if (adpJianDuJianChaListAdapter.getItem(position) != null
                            && adpJianDuJianChaListAdapter.getItem(position) instanceof JianDuJianChaRecord) {

                        JianDuJianChaRecord record = (JianDuJianChaRecord) adpJianDuJianChaListAdapter
                                .getItem(position);

                        record.setState(1);

                        activity.toEdit(record);

                    }

                }

            }

            if (v.getId() == R.id.btnDaiShangChuanUpload) {
                CustomDialog progressDialog = null;
                progressDialog = new CustomDialog(getActivity());

                progressDialog.setMessage("正在上传...");

                progressDialog.setCanceledOnTouchOutside(false);

                progressDialog.setWidthPercent(0.6F);

                progressDialog.setTitle(null);

                progressDialog.setActionTxt(null);

                progressDialog.setCancleTxt(null);

                progressDialog.showWait();


                if (user.isTester()) {

                    DialogUtil.showMessageDialog("演示账户禁止上传..", null,
                            getActivity());

                    return;
                }

                int position = (Integer) v.getTag();

                // 获得每一项的跟布局
                View itemView = lvJianDuJianChaDaiShangChuanList
                        .getChildAt(position - lvJianDuJianChaDaiShangChuanList.getFirstVisiblePosition());

                DaiShangChuanListAdapter adpJianDuJianChaListAdapter = (DaiShangChuanListAdapter) lvJianDuJianChaDaiShangChuanList
                        .getAdapter();

                if (adpJianDuJianChaListAdapter.getItem(position) != null
                        && adpJianDuJianChaListAdapter.getItem(position) instanceof JianDuJianChaRecord) {

                    JianDuJianChaRecord record = (JianDuJianChaRecord) adpJianDuJianChaListAdapter
                            .getItem(position);

                    // 查询到上传的地址
                    String uploadUrl = new ConfigUtil(getResources())
                            .getPreHttpUrl()
                            + getActivity().getResources().getString(
                            R.string.upload_address);

                    // 验证的用户名
                    String authUserName = new ConfigUtil(getResources())
                            .getRestUsername();

                    // 验证的密码
                    String authPassword = new ConfigUtil(getResources())
                            .getRestPassword();

                    // JSON 数据
                    String jsonData = null;

                    // JSON对象
                    JSONObject jsonObject = new JSONObject();
                    try {

                        jsonObject.put("add_from", 1);

                        jsonObject.put("add_user", user.getUsername());

                        jsonObject.put("_method", "post");

                        // 开始拼接字符串
                        jsonObject.put("region_code", record.getKnowTown()
                                .getCode());

                        String timeOld = record.getTime();

                        if (!CharsetUtil.isNotNull(timeOld)) {

                            timeOld = new SimpleDateFormat("yyyy-MM-dd")
                                    .format(new Date());

                        }

                        // 进行时间的转换
                        Date oldTimeDate = null;

                        try {
                            oldTimeDate = new SimpleDateFormat("yyyy-MM-dd")
                                    .parse(timeOld);

                        } catch (java.text.ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        String timeNew = new SimpleDateFormat("yyyy-MM-dd")
                                .format(oldTimeDate);

                        jsonObject.put("date", timeNew);

                        // 被检单位合集
                        JSONArray enterpriseJsonObjectArray = new JSONArray();

                        JSONObject enterpriseJsonObject = new JSONObject();

                        enterpriseJsonObject.put("autoCreate", record
                                .getBeiJianDanWei().isCreateShouJianDanWei());

                        enterpriseJsonObject.put("name", record
                                .getBeiJianDanWei().getName());

                        // 不创建并且填写信息的时候
                        if (record.getBeiJianDanWei().isCreateShouJianDanWei()) {
                            enterpriseJsonObject.put("address", record
                                    .getBeiJianDanWei().getAddress());
                            enterpriseJsonObject.put("charge", record
                                    .getBeiJianDanWei().getCharge());
                            enterpriseJsonObject.put("tel", record
                                    .getBeiJianDanWei().getMobile());
                        }

                        enterpriseJsonObjectArray.put(enterpriseJsonObject);

                        jsonObject.put("enterprise", enterpriseJsonObjectArray);

                        // 检查单位合集
                        JSONArray department = new JSONArray();

                        for (JianChaDanWei jcdw : record.getJianChaDanWeis()) {

                            department.put(jcdw.getName());
                        }

                        jsonObject.put("department", department);

                        // 检查人员合集
                        JSONArray inspector = new JSONArray();

                        for (JianChaRenYuan jcry : record.getJianChaReYuans()) {

                            inspector.put(jcry.getName());
                        }

                        jsonObject.put("inspector", inspector);

                        // 检查内容的合集
                        JSONArray category = new JSONArray();

                        for (JianChaNeiRong jcnr : record.getJianChaNeiRongs()) {
                            category.put(jcnr.getId());
                        }

                        jsonObject.put("category", category);

                        // 检查行业的合集
                        JSONArray trade = new JSONArray();

                        for (JianChaHangYe jchy : record.getJianChaHangYes()) {
                            trade.put(jchy.getId());
                        }

                        jsonObject.put("trade", trade);

                        // 产地环境安全
                        JSONObject environment = new JSONObject();

                        if (record.getJianChaJieGuos()[0] != null) {

                            if (record.getJianChaJieGuos()[0].getId() == null) {

                                environment.put("result", 0);

                            } else {

                                environment.put("result",
                                        record.getJianChaJieGuos()[0].getId());
                            }

                            if (!CharsetUtil.isNotNull(record
                                    .getJianChaJieGuos()[0].getProblem())) {

                                environment.put("problem", "");

                            } else {

                                environment.put("problem", record
                                        .getJianChaJieGuos()[0].getProblem());
                            }

                        } else {
                            environment.put("result", 0);
                            environment.put("problem", "");

                        }

                        jsonObject.put("environment", environment);

                        // 产地经营的规范性
                        JSONObject operate = new JSONObject();

                        if (record.getJianChaJieGuos()[1] != null) {

                            if (record.getJianChaJieGuos()[1].getId() == null) {
                                operate.put("result", 0);
                            } else {

                                operate.put("result",
                                        record.getJianChaJieGuos()[1].getId());
                            }

                            if (!CharsetUtil.isNotNull(record
                                    .getJianChaJieGuos()[1].getProblem())) {

                                operate.put("problem", "");

                            } else {

                                operate.put("problem", record
                                        .getJianChaJieGuos()[1].getProblem());
                            }

                        } else {
                            operate.put("result", 0);
                            operate.put("problem", "");

                        }

                        jsonObject.put("operate", operate);

                        // 产地质量安全性
                        JSONObject quality = new JSONObject();

                        if (record.getJianChaJieGuos()[2] != null) {

                            if (record.getJianChaJieGuos()[2].getId() == null) {
                                quality.put("result", 0);
                            } else {

                                quality.put("result",
                                        record.getJianChaJieGuos()[2].getId());
                            }

                            if (!CharsetUtil.isNotNull(record
                                    .getJianChaJieGuos()[2].getProblem())) {

                                quality.put("problem", "");

                            } else {

                                quality.put("problem", record
                                        .getJianChaJieGuos()[2].getProblem());
                            }

                        } else {
                            quality.put("result", 0);
                            quality.put("problem", "");

                        }

                        jsonObject.put("quality", quality);

                        // 产地包装合法性
                        JSONObject mark = new JSONObject();

                        if (record.getJianChaJieGuos()[3] != null) {

                            if (record.getJianChaJieGuos()[3].getId() == null) {
                                mark.put("result", 0);
                            } else {

                                mark.put("result",
                                        record.getJianChaJieGuos()[3].getId());
                            }

                            if (!CharsetUtil.isNotNull(record
                                    .getJianChaJieGuos()[3].getProblem())) {

                                mark.put("problem", "");

                            } else {

                                mark.put("problem",
                                        record.getJianChaJieGuos()[3]
                                                .getProblem());
                            }

                        } else {
                            mark.put("result", 0);
                            mark.put("problem", "");

                        }

                        jsonObject.put("mark", mark);

                        // 其他
                        JSONObject other = new JSONObject();

                        if (record.getJianChaJieGuos()[4] != null) {

                            if (record.getJianChaJieGuos()[4].getId() == null) {
                                other.put("result", 0);
                            } else {

                                other.put("result",
                                        record.getJianChaJieGuos()[4].getId());
                            }

                            if (!CharsetUtil.isNotNull(record
                                    .getJianChaJieGuos()[4].getProblem())) {

                                other.put("problem", "");

                            } else {

                                other.put("problem",
                                        record.getJianChaJieGuos()[4]
                                                .getProblem());
                            }

                        } else {
                            other.put("result", 0);
                            other.put("problem", "");

                        }

                        jsonObject.put("other", other);

                        // 日常监管
                        JSONObject inspection = new JSONObject();

                        if (record.getRiChangJianGuan() != null) {

                            if (record.getRiChangJianGuan().getId() == null) {
                                inspection.put("result", 0);
                            } else {

                                inspection.put("result", record
                                        .getRiChangJianGuan().getId());
                            }

                            if (!CharsetUtil.isNotNull(record
                                    .getRiChangJianGuan().getProblem())) {

                                inspection.put("problem", "");

                            } else {

                                inspection.put("problem", record
                                        .getRiChangJianGuan().getProblem());
                            }

                            if (!CharsetUtil.isNotNull(record.getJianChaJiLu())) {

                                inspection.put("content", "");

                            } else {

                                inspection.put("content",
                                        record.getJianChaJiLu());
                            }

                        } else {

                            if (!CharsetUtil.isNotNull(record.getJianChaJiLu())) {

                                inspection.put("content", "");

                            } else {

                                inspection.put("content",
                                        record.getJianChaJiLu());
                            }
                            inspection.put("result", 0);
                            inspection.put("problem", "");

                        }

                        jsonObject.put("inspection", inspection);

                        JSONObject measure = new JSONObject();

                        if (CharsetUtil.isNotNull(record.getZhengGaiYiJian())) {

                            measure.put("opinion", record.getZhengGaiYiJian());

                        } else {
                            measure.put("opinion", "");
                        }

                        measure.put("content", "");
                        measure.put("result", "");
                        measure.put("date", "");

                        jsonObject.put("measure", measure);

                        jsonObject.put("add_sign", ImageUtil
                                .bitToBase64FromFile(record.getQianMingPath()));

                        JSONArray photos = new JSONArray();

                        for (Photo photo : record.getUploadPhoto()) {

                            JSONObject photoJsonObj = new JSONObject();

                            photoJsonObj.put("base64", ImageUtil
                                    .bitToBase64FromFile(photo
                                            .getBigPhotoPath()));
                            photoJsonObj.put("comment", photo.getComment());
                            photoJsonObj.put("time", photo.getPhotoTime());
                            photoJsonObj
                                    .put("position", photo.getAddressDesc());
                            photoJsonObj.put("longitude", photo.getLongitude());
                            photoJsonObj.put("latitude", photo.getLatitude());

                            photos.put(photoJsonObj);

                        }
                        jsonObject.put("photo", photos);

                        jsonData = jsonObject.toString();

                    } catch (JSONException e) {
                        jsonData = null;
                    } catch (ParseException e) {
                        jsonData = null;
                    }

                    // 启动任务
                    UploadDaiShangChuanTask task = new UploadDaiShangChuanTask(
                            itemView,
                            getActivity(),
                            record,
                            (DaiShangChuanListAdapter) lvJianDuJianChaDaiShangChuanList
                                    .getAdapter(), uploadUrl, jsonData,
                            authUserName, authPassword, progressDialog);

                    // 执行任务
                    task.execute();

                }

            }

        }

    }

}
